package org.squabble.web.account;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.validation.Validator;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.squabble.SquabbleConstants;
import org.squabble.domain.Account;
import org.squabble.exception.SquabbleSecurityException;
import org.squabble.service.AccountService;
import org.squabble.service.LoginService;

@Controller
@RequestMapping("/account/email")
@SessionAttributes(value = { "account" })
public class EmailChangeController {

	protected final Log logger = LogFactory.getLog(getClass());

	@Autowired
	@Qualifier("validator")
	Validator validator;

	@Autowired
	LoginService loginService;

//	@Autowired
//	ProviderManager providerManager;

	@Autowired
	AccountService accountService;

	@RequestMapping(method = RequestMethod.GET)
	public String setupForm(@ModelAttribute("account") Account account,
			ModelMap model) throws Exception {
		// TODO Auto-generated method stub
		EmailChangeCommand ecc = new EmailChangeCommand();
		ecc.setAccountId(account.getId());
		model.addAttribute("emailChangeCommand", ecc);
		return "account.email";
	}

	@RequestMapping(method = RequestMethod.POST)
	public String processSubmit(@ModelAttribute("account") Account account,
			@ModelAttribute("emailChangeCommand") EmailChangeCommand ecc,
			BindingResult result, ModelMap model, HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		validator.validate(ecc, result);
		if (result.hasErrors()) {
			return "account.email";
		}
		if (!account.getId().equals(ecc.getAccountId())) {
			throw new SquabbleSecurityException(
					"Account did not match when changing email address ("
							+ account.getId() + ", " + ecc.getAccountId() + ")");
		}
		accountService.updateEmail(account.getId(), ecc.getNewEmail());
		account = accountService.getAccount(account.getId());
		loginService.updateCookie(request, response, account);
		model.addAttribute(SquabbleConstants.POST_PROCESS_MESSAGE,
				"email.processed");
		return "redirect:/account/home";
	}

}
